<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/5/15 15:37
 * Email: <594652523@qq.com>
 */

namespace App\Console\Commands;

use App\Models\Campus;
use App\Models\CourseMessage;
use App\Models\CourseOrder;
use App\Models\CourseSection;
use App\Models\Users;
use EasyWeChat\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SendMessage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:message';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送上课提醒';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $app   = Factory::miniProgram(config('wechat.mini_program.default'));
        $start = strtotime(date('Y-m-d') . ' 00:00:00');
        $end   = strtotime(date('Y-m-d') . ' 23:59:59');
        CourseSection::where('status', 1)->where('send_status', 0)->where('begin_time', '>=', $start)->where('begin_time', '<=', $end)->orderBy('begin_time', 'asc')->orderBy('id', 'asc')->chunkById(100, function ($list) use ($start, $end, $app) {
            foreach ($list as $item) {
                Log::info('章节' . $item['id'] . '开始');
                CourseOrder::where('course_id', $item['course_id'])->orderBy('id', 'asc')->chunkById(100, function ($orders) use ($item, $app) {
                    foreach ($orders as $order) {
                        $sendData = [
                            'touser'      => Users::where('id', $order['user_id'])->value('openid'),
                            'template_id' => 'HtCd3_f2R2EUBeffKXm_c9YsUz0yg49E-iwA3s1l3Zw',
                            'data'        => [
                                'thing11' => $item['name'],
                                'time10'  => $item['class_time'] . ' ' . $item['begin_time'],
                                'thing3'  => Campus::where('id', $order['campus_id'])->value('address'),
                                'thing4'  => '上课记得打卡签到哟，获积分可兑换权益',
                            ],
                            'page'        => 'pages/campus/index'
                        ];

                        //发送给用户对应的关联者
                        $rel = $app->subscribe_message->send($sendData);
                        Log::info('服务通知结果', ['rel' => json_encode($rel), 'send_data' => json_encode($sendData['data'])]);
                    }
                });
                $item->send_status = 1;
                $item->save();
            }

        });


    }

}
